const Course = require('../../database/models/course');

class CourseService {
  constructor(db) {
    this.courseModel = new Course(db);
  }

  /**
   * Initialize the course service
   */
  async init() {
    await this.courseModel.initTables();
  }

  /**
   * Create a new course
   * @param {Object} courseData - Course data to create
   * @returns {Promise} - Promise that resolves with the created course ID
   */
  async createCourse(courseData) {
    try {
      return await this.courseModel.createCourse(courseData);
    } catch (err) {
      throw new Error(`Failed to create course: ${err.message}`);
    }
  }

  /**
   * Get a course by ID
   * @param {number} id - Course ID
   * @returns {Promise} - Promise that resolves with the course data
   */
  async getCourseById(id) {
    try {
      return await this.courseModel.getCourseById(id);
    } catch (err) {
      throw new Error(`Failed to get course by ID: ${err.message}`);
    }
  }

  /**
   * Get all courses
   * @returns {Promise} - Promise that resolves with all courses
   */
  async getAllCourses() {
    try {
      return await this.courseModel.getAllCourses();
    } catch (err) {
      throw new Error(`Failed to get all courses: ${err.message}`);
    }
  }

  /**
   * Create a curriculum item
   * @param {Object} curriculumData - Curriculum data to create
   * @returns {Promise} - Promise that resolves with the created curriculum ID
   */
  async createCurriculumItem(curriculumData) {
    try {
      return await this.courseModel.createCurriculumItem(curriculumData);
    } catch (err) {
      throw new Error(`Failed to create curriculum item: ${err.message}`);
    }
  }

  /**
   * Get curriculum items for a course
   * @param {number} courseId - Course ID
   * @param {number|null} parentId - Parent ID (null for root items)
   * @returns {Promise} - Promise that resolves with curriculum items
   */
  async getCurriculumItems(courseId, parentId = null) {
    try {
      return await this.courseModel.getCurriculumItems(courseId, parentId);
    } catch (err) {
      throw new Error(`Failed to get curriculum items: ${err.message}`);
    }
  }
}

module.exports = CourseService;
